import React, { Component } from 'react';
import {observer,inject} from 'mobx-react'

@inject("store")
@observer
class Home extends Component {
    handleTodos=(type)=>{
        const {store}=this.props
        console.log(type);
        const inp=this.refNameRef.current// 获取到input输入框
        switch (type) {// 根据按钮参数 调用 store 对应的action方法
            case 'add':
                store.addList(inp.value) ; 
                inp.value='';//结束后清空输入框的值
                break;
            case 'del':store.delList() ; break;
            case 'clear':store.clearList() ; break;
            default: ; break;
        }
    }
    setFinished=(item,event)=>{//设置当前项的完成状态
        const {store}=this.props
        store.changeFinished(item.id)//调用store的computed方法 传入id 
    }
    refNameRef = React.createRef()// 创建input输入框的ref
    
    render() {
        const {store}=this.props
        return (
            <div>
                <h2>TodoList</h2>
                {/* 获取computed */}
                <p>共{store.todos.length},未完成{store.unFinished}</p>
                <input type="text" ref={this.refNameRef}/>
                <button onClick={this.handleTodos.bind(this,'add')}>添加</button>
                <button onClick={this.handleTodos.bind(this,'del')}>删除</button>
                <button onClick={this.handleTodos.bind(this,'clear')}>清空</button>
                {
                    // 遍历todos 并展示
                    store.todos.map((item,index)=>(
                        <div key={index}>
                            <label htmlFor={'todo'+item.id}>
                                <input 
                                    type="checkbox" 
                                    id={'todo'+item.id} 
                                    // 改变 当前项 完成状态
                                    onChange={this.setFinished.bind(this,item)}
                                    checked={item.done}
                                />
                                {item.title}
                            </label>
                        </div>
                    ))
                }
            </div>
        );
    }
}

export default Home;
